<!--
  Copyright 2018 The Outline Authors

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<link rel='import' href='../bower_components/polymer/polymer.html'>
<link rel="import" href="../bower_components/app-layout/app-drawer/app-drawer.html">
<link rel='import' href='../bower_components/iron-icon/iron-icon.html'>
<link rel='import' href='../bower_components/iron-icons/iron-icons.html'>
<link rel='import' href='../bower_components/iron-pages/iron-pages.html'>
<link rel='import' href='../bower_components/paper-icon-button/paper-icon-button.html'>
<link rel='import' href='../bower_components/paper-toast/paper-toast.html'>
<link rel='import' href='../bower_components/paper-dialog/paper-dialog.html'>
<link rel='import' href='../bower_components/paper-dialog-scrollable/paper-dialog-scrollable.html'>
<link rel='import' href='../bower_components/paper-listbox/paper-listbox.html'>

<link rel="import" href="./cloud-install-styles.html">
<link rel="import" href="./outline-about-dialog.html">
<link rel="import" href="./outline-do-oauth-step.html">
<link rel="import" href="./outline-feedback-dialog.html">
<link rel="import" href="./outline-intro-step.html">
<link rel="import" href="./outline-manual-server-entry.html">
<link rel="import" href="./outline-modal-dialog.html">
<link rel="import" href="./outline-region-picker-step.html">
<link rel="import" href="./outline-server-progress-step.html">
<link rel="import" href="./outline-server-view.html">
<link rel="import" href="./outline-tos-view.html">

<dom-module id="app-root">
  <template>
    <style include='cloud-install-styles'></style>
    <style>
      :host {
        width: 100%;
        --primary-green: #00bfa5;
        --light-gray: color: rgba(0,0,0,0.54);
      }
      #toast {
        align-items: center;
        display: flex;
        justify-content: space-between;
        padding: 24px;
        max-width: 450px;
      }
      #toast paper-icon-button {
        /* prevents the icon from resizing when there is a long message in the toast */
        flex-shrink: 0;
        padding: 0;
        height: 20px;
        width: 20px;
      }
      #settingsDrawer {
        z-index: 1000;
        margin-top: 12px;
      }
      #settingsDrawer paper-listbox {
        color: var(--light-gray);
      }
      #settingsDrawer paper-icon-item {
        display: block;
        cursor: pointer;
        padding: 12px 24px 12px 24px;
        font-size: 14px;
      }
      #settingsDrawer iron-icon {
        margin-right: 12px;
      }
      #settingsDrawer paper-icon-item:hover,
      #settingsDrawer paper-icon-item iron-icon:hover {
        color: var(--primary-green);
      }
      #settingsDrawer a {
        color: inherit;
      }
      #settingsDrawer paper-icon-item:focus,
      #settingsDrawer a:focus {
        outline: none;
      }
      #settingsDrawer #signedIn {
        text-align: center;
      }
      #settingsDrawer #signedIn img {
        height: 65px;
        margin-top: 12px;
      }
      #settingsDrawer #signOutButton  {
        font-weight: bold;
        margin-bottom: 24px;
        cursor: pointer;
        text-transform: uppercase;
      }
      #settingsDrawer #signOutButton:hover {
        color: var(--primary-green);
      }
      app-toolbar paper-icon-button {
        /* needed so the "Outline Manager" title appears centered in the window. */
        position: absolute;
      }
      app-toolbar [main-title] {
        text-align: center;
      }
      app-toolbar [main-title] img {
        height: 16px;
        margin-top: 8px;
      }
    </style>

    <outline-tos-view id="tosView" has-accepted-terms-of-service={{userAcceptedTos}} hidden$="{{hasAcceptedTos}}"></outline-tos-view>

    <div hidden$="{{!hasAcceptedTos}}">
      <app-drawer id="settingsDrawer">
        <div id='signedIn' hidden$='{{!isSignedIn}}'>
          <img src='images/manager-profile-2x.png'>
          <p>{{adminEmail}}</p>
          <div id='signOutButton' on-tap='signOutTapped'>Sign Out</div>
          <hr/>
        </div>
        <paper-listbox on-tap="closeSettingsDrawer">
          <a href="https://s3.amazonaws.com/outline-vpn/index.html#/en/support/dataCollection">
            <paper-icon-item>
              <iron-icon icon="lock" slot="item-icon"></iron-icon>Data Collection
            </paper-icon-item>
          </a>
          <a href="https://www.google.com/policies/privacy/">
            <paper-icon-item>
              <iron-icon icon="lock" slot="item-icon"></iron-icon>Privacy
            </paper-icon-item>
          </a>
          <a href="https://s3.amazonaws.com/outline-vpn/static_downloads/Outline-Terms-of-Service.html">
            <paper-icon-item>
                <iron-icon icon="info" slot="item-icon"></iron-icon>Terms
            </paper-icon-item>
          </a>
          <paper-icon-item on-tap="submitFeedbackTapped">
            <iron-icon icon="feedback" slot="item-icon"></iron-icon>Submit Feedback
          </paper-icon-item>
          <a href="https://s3.amazonaws.com/outline-vpn/index.html#/en/support/">
            <paper-icon-item>
              <iron-icon icon="help" slot="item-icon"></iron-icon>Help Center
            </paper-icon-item>
          </a>
          <paper-icon-item on-tap="aboutTapped">
            <iron-icon icon="info" slot="item-icon"></iron-icon>About Outline
          </paper-icon-item>
          <paper-icon-item on-tap="showLicensesTapped">
            <iron-icon icon="info" slot="item-icon"></iron-icon>Show Licenses
          </paper-icon-item>
        </paper-listbox>
      </app-drawer>

      <app-toolbar class='toolbar'>
        <paper-icon-button icon="menu" on-tap="toggleSettingsDrawer"></paper-icon-button>
        <div main-title><img src="images/outline-manager-logo.svg"></div>
      </app-toolbar>

      <iron-pages attr-for-selected='id' selected='{{ currentPage }}'>
        <outline-intro-step id='intro'></outline-intro-step>
        <outline-do-oauth-step id='digitalOceanOauth'></outline-do-oauth-step>
        <outline-manual-server-entry id='manualEntry'></outline-manual-server-entry>
        <outline-region-picker-step id='regionPicker'></outline-region-picker-step>
        <outline-server-progress-step id='serverProgressStep'></outline-server-progress-step>
        <outline-server-view id='serverView'></outline-server-view>
      </iron-pages>

      <paper-toast id='toast'><paper-icon-button icon='icons:close' on-tap='closeError'></paper-icon-button></paper-toast>

      <outline-feedback-dialog id='feedbackDialog'></outline-feedback-dialog>
      <outline-about-dialog id='aboutDialog' outline-version='[[outlineVersion]]'></outline-about-dialog>
      <outline-modal-dialog id='modalDialog'></outline-modal-dialog>

      <paper-dialog id="licenses" restoreFocusOnClose>
        <paper-dialog-scrollable>
          <code id="licensesText">
            Could not load license.txt.
          </code>
        </paper-dialog-scrollable>
        <div class="buttons">
          <paper-button dialog-dismiss autofocus>Close</paper-button>
        </div>
      </paper-dialog>
    </div>
  </template>
  <script>
    const TOS_ACK_LOCAL_STORAGE_KEY = 'tos-ack';
    Polymer({
      is: 'app-root',
      properties: {
        adminEmail: {
          type: String,
          value: ''
        },
        isSignedIn: {
          type: Boolean,
          computed: '_isSignedIn(adminEmail)'
        },
        outlineVersion: String,
        userAcceptedTos: {
          type: Boolean,
           // Get notified when the user clicks the OK button in the ToS view
          observer: '_userAcceptedTosChanged',
        },
        hasAcceptedTos: {
          type: Boolean,
          computed: '_computeHasAcceptedTermsOfService(userAcceptedTos)'
        },
        currentPage: {
          type: String,
          value: 'intro'
        }
      },
      listeners: {
        'RegionSelected': 'handleRegionSelected',
        'MetricsChoiceSelected': 'handleMetricsChoiceSelected',
        'SetUpGenericCloudProviderRequested': 'handleSetUpGenericCloudProviderRequested',
        'SetUpAwsRequested': 'handleSetUpAwsRequested',
        'SetUpGcpRequested': 'handleSetUpGcpRequested',
        'ManualServerEntryCancelled': 'handleManualCancelled'
      },
      showIntro: function () {
        this.currentPage = 'intro';
      },
      getDigitalOceanOauthFlow: function (onCancel) {
        const oauthFlow = this.$.digitalOceanOauth;
        oauthFlow.onCancel = onCancel;
        return oauthFlow;
      },
      showDigitalOceanOauthFlow: function () {
        this.currentPage = 'digitalOceanOauth';
      },
      getAndShowDigitalOceanOauthFlow: function (onCancel) {
        this.currentPage = 'digitalOceanOauth';
        const oauthFlow = this.getDigitalOceanOauthFlow(onCancel);
        oauthFlow.showConnectAccount();
        return oauthFlow;
      },
      getAndShowRegionPicker: function () {
        this.currentPage = 'regionPicker';
        this.$.regionPicker.init();
        return this.$.regionPicker;
      },
      getManualServerEntry: function() {
        return this.$.manualEntry;
      },
      showProgress: function (serverName, showCancelButton) {
        this.currentPage = 'serverProgressStep';
        this.$.serverProgressStep.serverName = serverName;
        this.$.serverProgressStep.showCancelButton = showCancelButton;
        this.$.serverProgressStep.start();
      },
      showServerView: function () {
        this.$.serverProgressStep.stop();
        this.$.serverView.initHelpBubbles();
        this.currentPage = 'serverView';
      },
      getServerView: function() {
        return this.$.serverView;
      },
      handleRegionSelected: function (e) {
        this.fire('SetUpServerRequested', {
          regionId: this.$.regionPicker.getSelectedRegionId()
        });
      },
      handleSetUpGenericCloudProviderRequested: function () {
        this.handleManualServerSelected('generic');
      },
      handleSetUpAwsRequested: function() {
        this.handleManualServerSelected('aws');
      },
      handleSetUpGcpRequested: function() {
        this.handleManualServerSelected('gcp');
      },
      handleManualServerSelected: function(cloudProvider) {
        this.$.manualEntry.clear();
        this.$.manualEntry.cloudProvider = cloudProvider;
        this.currentPage = 'manualEntry';
      },
      handleManualCancelled: function() {
        this.currentPage = 'intro';
      },
      showError: function (errorMsg) {
        this.showToast(errorMsg, Infinity);
      },
      showNotification: function (message) {
        const NOTIFICATION_TOAST_DURATION_MS = 3000;
        this.showToast(message, NOTIFICATION_TOAST_DURATION_MS);
      },
      showToast: function(message, duration) {
        const toast = this.$.toast;
        toast.close();
        // Defer in order to trigger the toast animation, otherwise the
        // update happens in place.
        setTimeout(() => {
          toast.show({
            text: message,
            duration: duration,
            noOverlap: true
          });
        }, 0);
      },
      closeError: function () {
        this.$.toast.close();
      },
      // cb is a function which accepts a single boolean which is true iff
      // the user chose to retry the failing operation.
      showConnectivityDialog: function (cb) {
        const dialogTitle = 'Connection problem';
        const dialogText = 'We\'re having trouble connecting with your DigitalOcean account. This is often a temporary problem with DigitalOcean or with your internet connection. In some cases, logging into DigitalOcean again will fix the problem.';
        this.showModalDialog(dialogTitle, dialogText, ['login', 'retry'])
        .then((clickedButtonIndex) => {
          cb(clickedButtonIndex === 1);  // pass true if user clicked retry
        });
      },
      getConfirmation: function(title, text, confirmButtonText, continueFunc) {
        this.showModalDialog(title, text, ['Cancel', confirmButtonText])
        .then((clickedButtonIndex) => {
          if (clickedButtonIndex === 1) {  // user clicked to confirm.
            continueFunc();
          }
        });
      },
      _isSignedIn: function (adminEmail) {
        return Boolean(adminEmail);
      },
      _userAcceptedTosChanged: function(userAcceptedTos) {
        if (userAcceptedTos) {
          window.localStorage[TOS_ACK_LOCAL_STORAGE_KEY] = Date.now();
        }
      },
      _computeHasAcceptedTermsOfService: function(userAcceptedTos) {
        return userAcceptedTos || !!window.localStorage[TOS_ACK_LOCAL_STORAGE_KEY];
      },
      toggleSettingsDrawer: function() {
        this.$.settingsDrawer.toggle();
      },
      closeSettingsDrawer: function() {
        this.$.settingsDrawer.close();
      },
      submitFeedbackTapped: function () {
        this.$.feedbackDialog.open();
      },
      aboutTapped: function() {
        this.$.aboutDialog.open();
      },
      signOutTapped: function() {
        this.closeSettingsDrawer();
        this.fire('SignOutRequested');
      },
      openManualInstallFeedback: function(prepopulatedMessage) {
        this.$.feedbackDialog.open(prepopulatedMessage, true);
      },
      // Returns a Promise which fulfills with the index of the button clicked.
      showModalDialog: function(title, text, buttons) {
        return this.$.modalDialog.open(title, text, buttons);
      },
      closeModalDialog: function(title, text, buttons) {
        return this.$.modalDialog.close();
      },
      showLicensesTapped: function () {
        this.closeSettingsDrawer();
        var xhr = new XMLHttpRequest();
        xhr.onload = () => {
          this.$.licensesText.innerText = xhr.responseText;
          this.$.licenses.open();
        };
        xhr.onerror = () => {
          console.error('could not load license.txt');
        };
        xhr.open('GET', '/ui_components/licenses/licenses.txt', true);
        xhr.send();
      }
    });
  </script>
</dom-module>
